import os.path
import sys
import matplotlib.pyplot as plt
import numpy as np
from generate_analyseWLs import get_csv_names

with open('picked_filenames_rdPct0.80_0.85__writeNum1000000.txt', 'r') as f:
    csv_names_str = f.readline()
csv_names = csv_names_str.split()


csv_names, _ = get_csv_names()
for i in range(len(csv_names)):
    if csv_names[i] == '562950162059084.csv':
    # if csv_names[i] == '562950010336160.csv':
        pass


# mem = 0
# for i in range(5, 15):
#     mem = mem + sizes[i]
# print(mem)

# 这一段分析的时候才加
# plt.subplot(121)
# plt.plot(sizes)
# plt.title(len(sizes))
# plt.subplot(122)
# mem = [3*np.array(sizes[:i]).sum() for i in range(len(sizes))]
# plt.plot(mem)
# plt.xlabel('samples to accumulate')
# plt.ylabel('approximate mem in GB')
# plt.show()


def generate_start_step(START, STEP, script_name):
    f = open(script_name, 'w')
    sys.stdout = f

    print('#!/bin/bash')
    print('start_time=$(date +%s)\n')

    filenames = ''
    for i in range(STEP):
        filenames += csv_names[START+i] + ' '

    print('#', START, STEP)

    # load1
    print('sync; echo 3 | sudo tee /proc/sys/vm/drop_caches')
    cmd = ''
    for i in range(STEP):
        cmd += "sudo ./scripts/load_one.sh %s & " % csv_names[START+i]
    print(cmd)
    print('wait\necho load完成\n')

    print('sync; echo 3 | sudo tee /proc/sys/vm/drop_caches')
    cmd = ''
    for i in range(STEP):
        cmd += "sudo ./scripts/run_lsm_one.sh %s & " % csv_names[START+i]
    print(cmd)
    print('wait\necho run_lsm完成\n')

    # load2
    print('sync; echo 3 | sudo tee /proc/sys/vm/drop_caches')
    cmd = ''
    for i in range(STEP):
        cmd += "sudo ./scripts/load_one.sh %s & " % csv_names[START+i]
    print(cmd)
    print('wait\necho load完成\n')

    print('sync; echo 3 | sudo tee /proc/sys/vm/drop_caches')
    cmd = ''
    for i in range(STEP):
        cmd += "sudo ./scripts/run_baseline_one.sh %s & " % csv_names[START+i]
    print(cmd)
    print('wait\necho run_baseline完成\n')

    print('# 下面的是统计性能，fork自all_trace.sh')
    print('path=../data/ebs_segment_io_records/AY283G_2022-01-01_00:00:00_2022-01-02_00:00:00/device/\n')


    print('for filename in %s; do' % filenames)
    print('  data_path=${path}${filename}')
    print('  data_name=${filename%.*}')
    print('  for executable_file in trace_allGet trace_allPut trace_realRun ; do')
    print('    python ./scripts/collect_results.py 1 ${data_name}_${executable_file}_16 > ../evaluation/expr_${data_name}_${executable_file}_16.txt &')
    print('  done')
    print('done')
    print('wait\n')


    print('for filename in %s; do' % filenames)
    print('  data_path=${path}${filename}')
    print('  data_name=${filename%.*}')
    print('  for executable_file in trace_allGet trace_allPut trace_realRun ; do')
    print('    cat ../evaluation/expr_${data_name}_${executable_file}_16.txt')
    print('  done')
    print('  # plot iteration decay')
    print('  python ./scripts/plot2_iterationDecay.py ${data_name}')
    print('done\n')

    # print('# 整体的plot')
    # print('python ./scripts/plot3_mean_and_speedUp.py', START, STEP)

    print('\n# 结束，统计时间')
    print('end_time=$(date +%s)')
    print('cost_time=$((end_time-start_time))')
    print('echo "$0" "运行时间：$((cost_time/60))min $((cost_time%60))s"')
    new_evaluation_global = '../evaluation_global_picked_' + filenames.split()[0].split('.')[0] + '_' + str(START) + '_' + str(STEP) + 'tr/'
    print("newpath=%s" % new_evaluation_global)
    print("if [ ! -d ${newpath} ]; then")
    print('  mkdir %s' % new_evaluation_global)
    print("fi")
    print('mv %s %s' % ('../evaluation_global/*', new_evaluation_global))
    f.close()


if __name__ == "__main__":
    script_all_name = './scripts/step_picked.sh'
    with open(script_all_name, 'w') as f:
        f.write('#!/bin/bash\n')
        f.write('start_time=$(date +%s)\n')

    START = 164
    for step in [1, 2, 4]:
        script_single_name = './scripts/concurrent_run_picked%d_%d.sh' % (START, step)
        generate_start_step(START, step, script_single_name)

        with open(script_all_name, 'a') as f:
            f.write("chmod +x %s\n" % script_single_name)
            f.write("sudo %s\n" % script_single_name)

    with open(script_all_name, 'a') as f:
        f.write('end_time=$(date +%s)\n')
        f.write('cost_time=$((end_time-start_time))\n')
        f.write('echo "$0" "运行时间：$((cost_time/60))min $((cost_time%60))s"')
